/**
 * 
 */
package com.training.admin.security;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.demo2do.core.visitor.ObjectVisitor;
import com.training.admin.entity.principal.Principal;
import com.training.admin.entity.security.Login;
import com.training.admin.service.PrincipalService;

/**
 * 
 * @author downpour
 * 
 */
public class ApplicationAuthenticationProvider implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationAuthenticationProvider.class);

    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private ObjectVisitor objectVisitor;
    
    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
    @SuppressWarnings("unchecked")
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    	
         Principal principal = principalService.loadByName(username);
        
         if(principal == null) {
            throw new UsernameNotFoundException("未能找到用户");
         }
    	

        logger.info("ApplicationAuthenticationProvider#loadUserByUsername() - principal [" + principal.getUsername() + "] is found to login. ");
        
        // 1. construct Login by Principal
        Login login = new Login(principal);
        
              
        // ======= initialize other user properties =======
        Map<String, List<String>> resources = (Map<String, List<String>>) objectVisitor.evaluate("secure.resources['" + login.getAuthority() + "']");
        if(MapUtils.isNotEmpty(resources)) {
            login.initResources(resources);
        }
 
        return login;
    }

}
